﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using JoyxyAnalyzer.Utils;
using System.Collections.Specialized;

namespace JoyxyAnalyzer
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// 头信息字节长度
        /// </summary>
        public static int ITEM_HEADER_LEN = 7;

        #region Properties

        /// <summary>
        /// Log level enumeration
        /// </summary>
        enum LOG_LEVEL
        {
            NONE = -1,
            ERROR = 0,
            INFO = 1,
            WARNING = 2,
            DEBUG = 3
        };

        /// <summary>
        /// The selected item index for LOG Level
        /// </summary>
        private int selectedLogLevelNumber;

        #endregion 
        
        #region Constructor

        public MainForm()
        {
            InitializeComponent();
        }

        #endregion

        #region Business Logical

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="data"></param>
        /// <param name="fileMode"></param>
        public static void writeToFile(string fileName, List<string> data, FileMode fileMode)
        {
            writeToFile(fileName, null, data, fileMode);
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="meto"></param>
        /// <param name="data"></param>
        /// <param name="fileMode"></param>
        public static void writeToFile(string fileName, string meto, List<string> data, FileMode fileMode)
        {
            if (data != null)
            {
                FileStream fos = new FileStream(fileName, fileMode, FileAccess.Write);
                StreamWriter writer = new StreamWriter(fos);

                if (meto != null && meto != string.Empty)
                {
                    writer.WriteLine(meto);
                }

                foreach (string dat in data)
                {
                    writer.Write(dat);
                    writer.Write(" ");
                }

                writer.WriteLine();

                writer.Close();
                fos.Close();
            }
        }

        /// <summary>
        /// 获取英文文件字节
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="itemLen"></param>
        /// <param name="hexs"></param>
        /// <returns></returns>
        public static string getItemName(int offset, int itemLen, List<string> hexs)
        {
            List<string> hexStr = new List<string>();
            for (int itemIndex = 1; itemIndex <= itemLen; itemIndex++)
            {
                hexStr.Add(hexs[itemIndex + offset]);
            }

            return HexHelper.hexToString(hexStr);
        }

        /// <summary>
        /// 移动到下一个Item的坐标
        /// </summary>
        /// <param name="offset"></param>
        /// <param name="hexs"></param>
        /// <param name="includes"></param>
        /// <returns></returns>
        public int moveToNextItem(int offset, List<string> hexs, string[] includes)
        {
            int count = 0;
            string name = string.Empty;

            for (int i = offset; i < hexs.Count; i++)
            {
                // 匹配得到的字符串
                if (name != string.Empty && isStrMatched(name, includes))
                {
                    return i - count;
                }

                // 十六进制转成字符串
                string hexStr = HexHelper.hexToString(hexs[i]);
                if (isLegleChar(hexStr))
                {
                    name += hexStr;
                    count++;
                }
                else
                {
                    name = string.Empty;
                    count = 0;
                }
            }

            return -1;
        }

        /// <summary>
        /// 字符串是否匹配
        /// </summary>
        /// <param name="str"></param>
        /// <param name="patterns"></param>
        /// <returns></returns>
        public bool isStrMatched(string str, string[] patterns)
        {
            if (patterns != null)
            {
                foreach (string pattern in patterns)
                {
                    if (Regex.IsMatch(str, pattern.Trim()))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// 判断是否为合法字符
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public bool isLegleChar(string text)
        {
            return Regex.IsMatch(text, "[0-9A-Za-z|_|]+");
        }

        /// <summary>
        /// 判断是否含有字母
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public bool hasLetter(string text)
        {
            return Regex.IsMatch(text, "[a-z]+");
        }

        /// <summary>
        /// Loads the configuration from the config.ini file.
        /// </summary>
        /// <returns>the application configuration entity</returns>
        private ApplicationConfig loadConfig()
        {
            if (FileHelper.isFileExisted(ApplicationConfig.APP_CONFIG_FILE))
            {
                ApplicationConfig config = new ApplicationConfig();

                config.NmapFile = ApplicationConfig.IniHelper.ReadValue(ApplicationConfig.SECTION_GENERAL, "nmapFile");
                config.ExportFolder = ApplicationConfig.IniHelper.ReadValue(ApplicationConfig.SECTION_GENERAL, "exportFolder");

                StringCollection collections = ApplicationConfig.IniHelper.ReadSection(ApplicationConfig.SECTION_GENERAL);
                foreach (string key in collections)
                {
                    if (key.StartsWith("rule_"))
                    {
                        config.FilterNames.Add(key, ApplicationConfig.IniHelper.ReadValue(ApplicationConfig.SECTION_GENERAL, key));
                    }
                }

                return config;
            }

            return null;
        }

        /// <summary>
        /// Retruns true if the application configuration updated.
        /// </summary>
        /// <returns>true if the application configuration updated.</returns>
        private bool updateConfig()
        {
            if (ApplicationConfig.AppConfig != null)
            {
                ApplicationConfig.AppConfig.NmapFile = this.txtFile.Text.Trim();
                ApplicationConfig.AppConfig.ExportFolder = this.txtExportFolder.Text.Trim();

                ApplicationConfig.IniHelper.Write(ApplicationConfig.SECTION_GENERAL, "nmapFile", ApplicationConfig.AppConfig.NmapFile);
                ApplicationConfig.IniHelper.Write(ApplicationConfig.SECTION_GENERAL, "exportFolder", ApplicationConfig.AppConfig.ExportFolder);

                string fileName = Path.GetFileNameWithoutExtension(this.txtFile.Text.Trim());
                ApplicationConfig.AppConfig.FilterNames["rule_" + fileName] = this.txtAllowedItemPatterns.Text.Trim();

                foreach (string filterKey in ApplicationConfig.AppConfig.FilterNames.Keys)
                {
                    ApplicationConfig.IniHelper.Write(ApplicationConfig.SECTION_GENERAL, filterKey, ApplicationConfig.AppConfig.FilterNames[filterKey]);
                }

                return true;
            }

            return false;
        }

        #endregion 

        #region UI Logical

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "nmap文件|*.nmap";
            openFileDialog.RestoreDirectory = true;

            if (this.txtFile.Text.Trim() != string.Empty)
            {
                openFileDialog.FileName = this.txtFile.Text.Trim();
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                this.txtFile.Text = openFileDialog.FileName;
            }

            // 显现过滤规则
            string fileName = Path.GetFileNameWithoutExtension(this.txtFile.Text.Trim());
            if (!ApplicationConfig.AppConfig.FilterNames.ContainsKey("rule_" + fileName))
            {
                this.txtAllowedItemPatterns.Text = "";
                ApplicationConfig.AppConfig.FilterNames.Add("rule_" + fileName, "");
            }
            else
            {
                this.txtAllowedItemPatterns.Text = ApplicationConfig.AppConfig.FilterNames["rule_" + fileName];
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.comboBox1.SelectedItem = LOG_LEVEL.DEBUG.ToString();

            init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            ApplicationConfig.AppConfig = loadConfig();

            updateForm();
        }

        /// <summary>
        /// Validates the input values
        /// </summary>
        /// <returns></returns>
        private bool validateInputs()
        {
            log("验证输入...", LOG_LEVEL.INFO);

            if (this.txtFile.Text.Trim() == string.Empty || !File.Exists(this.txtFile.Text.Trim()))
            {
                log("nmap文件不存在.", LOG_LEVEL.ERROR);
                MessageBox.Show("nmap文件不存在",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtFile.Focus();
                return false;
            }

            if (this.txtExportFolder.Text.Trim() == string.Empty || !new DirectoryInfo(this.txtExportFolder.Text.Trim()).Exists)
            {
                log("导出文件夹不存在.", LOG_LEVEL.ERROR);
                MessageBox.Show("导出文件夹不存在",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtExportFolder.Focus();
                return false;
            }

            if (this.txtAllowedItemPatterns.Text.Trim() == string.Empty)
            {
                log("允许出现元素未定义.", LOG_LEVEL.ERROR);
                MessageBox.Show("允许出现元素未定义",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtAllowedItemPatterns.Focus();
                return false;
            }

            return true;
        }

        /// <summary>
        /// Refreshs the property of enable on componenets
        /// </summary>
        /// <param name="compEnabled"></param>
        private void updateForm(bool compEnabled)
        {
            this.txtFile.Enabled = compEnabled;
            this.txtAllowedItemPatterns.Enabled = compEnabled;
            this.comboBox1.Enabled = compEnabled;
            this.btnOpenFile.Enabled = compEnabled;
            this.btnStart.Enabled = compEnabled;
            this.txtExportFolder.Enabled = compEnabled;
            this.btnBrowser.Enabled = compEnabled;
        }

         /// <summary>
        /// Run
        /// </summary>
        private void doStart()
        {
            this.richTextBox1.Clear();

            // Validating inputs
            if (!this.validateInputs())
            {
                return;
            }

            // 保存配置, 供下次执行回忆
            this.updateConfig();

            // 不同的nmap文件可能需要定义不同的过滤规则....
            string[] includes = this.txtAllowedItemPatterns.Text.Trim().Split(','); 
            string nmapFile = this.txtFile.Text.Trim();
            string fileName = Path.GetFileNameWithoutExtension(nmapFile);

            // 读取字节
            List<byte> bytes = new List<byte>();

            try
            {
                // 二进制读取文件
                log("二进制读取nmap文件...");
                FileStream fos = new FileStream(nmapFile, FileMode.Open);
                BinaryReader reader = new BinaryReader(fos);
                try
                {
                    while (true)
                    {
                        bytes.Add(reader.ReadByte());
                    }
                }
                catch (EndOfStreamException ex)
                {
                    // do nothing here
                }

                // 关闭文件流
                reader.Close();
                fos.Close();
            }
            catch (Exception ex)
            {
                log("读取文件发生错误了:" + ex.Message, LOG_LEVEL.ERROR);

                MessageBox.Show("读取文件时发生错误了:" + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                updateForm(true);
                return;
            }

            log("nmap文件已成功读取...");

            // 获取十六进制
            List<string> hexs = HexHelper.byteToHexString(bytes);

            // 定义真实元素起始坐标
            int offset = -1;

            // 过滤头部信息
            log("过滤文件头信息...");
            for (int index = 0; index < hexs.Count; index++)
            {
                string hex = hexs[index];

                if (hex.StartsWith("0") && !hex.EndsWith("0"))
                {
                    // 英文文件名长度
                    int len = HexHelper.hexToDec(hex);

                    // 获取英文文件字节
                    string headerName = getItemName(index, len, hexs);

                    log("文件头: " + headerName);

                    // 根据解析的规则, 过滤头部的英文文件有多余的两个字节
                    offset = index + len + 2;

                    break;
                }
            }

            // 拆解元素
            log("拆解分段元素信息...");
            offset = ITEM_HEADER_LEN + offset;

            // 元素是否已经写入的标记
            bool isRecorded = false;

            // 拆解的元素计数器
            int itemCount = 1;

            // 定义装载所有已解析的元素容器
            List<ItemEntity> allItems = new List<ItemEntity>();

            for (int index = offset; index < hexs.Count - offset && index > -1; index++)
            {
                int len = HexHelper.hexToDec(hexs[index]);

                // 获取Item名字
                string itemName = getItemName(index, len, hexs);

                // 获取下一个Item的起始位置
                int nextItemIndex = moveToNextItem(index + len + 1, hexs, includes);

                // 定义Container
                List<string> itemHex = null;

                if (nextItemIndex == -1)
                {
                    // 文件结尾
                    itemHex = hexs.GetRange(index - ITEM_HEADER_LEN + 1, hexs.Count - index + ITEM_HEADER_LEN - 1);
                }
                else
                {

                    // 获取Item数据块, 并移除后一个Item的前置位
                    itemHex = hexs.GetRange(index - ITEM_HEADER_LEN + 1, nextItemIndex - index - 1);
                }

                if (itemHex != null && itemHex.Count > 0)
                {
                    try
                    {
                        // 写入文件
                        writeToFile(this.txtExportFolder.Text.Trim() + "\\" + fileName + "_items.txt", itemName, itemHex, isRecorded ? FileMode.Append : FileMode.OpenOrCreate);
                        isRecorded = true;

                        log("元素分段成功: " + itemName);
                        ItemEntity entity = convertFromFragment(itemName, itemHex, allItems);
                        if (entity != null)
                        {
                            allItems.Add(entity);

                            string csvFile = this.txtExportFolder.Text.Trim() + "\\" + fileName + ".csv";

                            if (!File.Exists(csvFile))
                            {
                                FileHelper.createFile(csvFile);
                            }

                            // 写入csv
                            writeToCsv(entity, csvFile, itemCount == 1 ? FileMode.Truncate : FileMode.Append, itemCount++);

                            log("分段数据已成功解析并写入CSV文件...");
                        }
                    }
                    catch (Exception ex)
                    {
                        log("解析`" + itemName + "`时发生错误了: " + ex.Message, LOG_LEVEL.ERROR);
                    }
                }

                index = nextItemIndex - 2;
            }


            log("拆解分段元素信息已结束...");

            MessageBox.Show("拆解元素成功.",
                    "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

            this.updateForm(true);
        }

        /// <summary>
        /// 写入CSV文件
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="csvFile"></param>
        /// <param name="mode"></param>
        /// <param name="seq"></param>
        private void writeToCsv(ItemEntity entity, string csvFile, FileMode mode, int seq)
        {
            if (entity != null)
            {
                FileStream csvFos = new FileStream(csvFile, mode, FileAccess.Write);
                using (StreamWriter fileWriter = new StreamWriter(csvFos))
                {
                    StringBuilder builder = new StringBuilder();

                    builder.Append(seq);
                    builder.Append(",");
                    builder.Append(entity.ItemNo); 
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment1);
                    builder.Append(",");
                    builder.Append(entity.ItemNameLen);
                    builder.Append(",");
                    builder.Append(entity.ItemName);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment2);
                    builder.Append(",");
                    builder.Append(entity.ItemX);
                    builder.Append(",");
                    builder.Append(entity.ItemY);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment3);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment4);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment5);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment6);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment7);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment8);
                    builder.Append(","); 
                    builder.Append(entity.UnknowFragment9);
                    builder.Append(",");
                    builder.Append(entity.UnknowFragment10);
                    builder.Append(",");
                    builder.Append(entity.ItemHex);

                    fileWriter.WriteLine(builder.ToString());
                    fileWriter.Flush();
                }

                csvFos.Close();
            }
        }

        /// <summary>
        /// 分段信息转为元素实体
        /// </summary>
        /// <param name="itemName"></param>
        /// <param name="fragment"></param>
        /// <param name="items"></param>
        /// <returns></returns>
        private ItemEntity convertFromFragment(string itemName, List<string> fragment, List<ItemEntity> items)
        {
            if (fragment != null && fragment.Count > 0)
            {
                ItemEntity entity = new ItemEntity();

                // 最后两位为元素编号
                entity.ItemNo = getDecFromFragmentSlice(fragment.Count - 2, 2, fragment, true).ToString();

                // 未知位信息1 - 偏移位? 第三字节位
                entity.UnknowFragment1 = getDecFromFragmentSlice(2, 2, fragment, true).ToString();

                // 元素名称
                entity.ItemName = itemName;

                // 元素长度
                entity.ItemNameLen = itemName.Length.ToString();

                // 除去头信息和文件名之后的起始索引点
                int offset = ITEM_HEADER_LEN + itemName.Length;

                // 未知位信息2 - 1个字节
                entity.UnknowFragment2 = HexHelper.hexToDec(fragment[offset]).ToString();

                // 移动偏移位, 中间过滤7个字节的占位符 + 位字节
                offset = offset + 7 + 1;

                // X坐标
                entity.ItemX = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 4个字节占位符 + X坐标位字节位
                offset = offset + 4 + 4;

                // Y坐标
                entity.ItemY = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 4个字节占位符 + X坐标位字节位
                offset = offset + 4;

                // 未知位信息3 - 4个字节
                entity.UnknowFragment3 = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 4个字节占位符 + 未知位信息3字节位
                offset = offset + 4 + 4;

                // 未知位信息4 - 4个字节
                entity.UnknowFragment4 = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 未知位信息4字节位
                offset = offset + 4;

                // 未知位信息5 - 4个字节
                entity.UnknowFragment5 = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 未知位信息5字节位
                offset = offset + 4;

                // 未知位信息6 - 4个字节
                entity.UnknowFragment6 = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 4个字节占位符 + 未知位信息6字节位
                offset = offset + 4 + 4;

                // 未知位信息7 - 4个字节
                entity.UnknowFragment7 = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 未知位信息7字节位
                offset = offset + 4;

                // 未知位信息8 - 4个字节
                entity.UnknowFragment8 = getDecFromFragmentSlice(offset, 4, fragment, true).ToString();

                // 移动偏移位 - 未知位信息8字节位
                offset = offset + 4;

                if (fragment.Count - offset > 15)
                {
                    // 超出预期的数据格式
                    // 00 00 CB 4B 00 00 0F 73 74 61 67 65 30 30 35 5F 30 30 32 61 5F 67 00 00 00 00 00 00 00 00 
                    // 28 00 00 00 00 00 00 00 EC FF FF FF 35 00 00 00 00 00 00 00 ,91 1F 00 00, 00 00 00 00 ,00 00 00 00, 02 00 00 00, 
                    // 0F 00 00 00, 0F 00 00 00, 00 00 00 00, 01 00 00 00, 
                    // 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 B8 D5 CC CC CC C9 C6 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 
                    // 01, FF FF FF FF, 48 07 
                    offset = fragment.Count - 7;
                }

                entity.UnknowFragment9 = getDecFromFragmentSlice(offset, 1, fragment, false).ToString();

                // 移动偏移位 - 未知位信息9字节位
                offset = offset + 1;

                // 未知位信息10 - 不固定长度, 可能0个字节, 可能多个字节
                if (fragment.Count - 2 - offset > 0)
                {
                    entity.UnknowFragment10 = getDecFromFragmentSlice(offset, fragment.Count - 2 - offset, fragment, true).ToString();
                }
                else
                {
                    entity.UnknowFragment10 = entity.ItemNo;
                }

                // 地图元素编号修正, 确保`mogu_mogu_a001`, `mogu_mogu_a0011`元素编号一致
                bool revised = false;
                string entityName = entity.ItemName;

                if (entityName.StartsWith("shuicao_qun_b"))
                {
                    Console.Write("Debug");
                }

                while (!revised)
                {
                    foreach (ItemEntity item in items)
                    {
                        if (entityName.StartsWith(item.ItemName) || item.ItemName.StartsWith(entityName))
                        {
                            entity.ItemNo = item.ItemNo;
                            log("修正元素编号: `" + entity.ItemName + " `to " + entity.ItemNo);
                            revised = true;
                            break;
                        }
                    }

                    int num = -1;
                    if (int.TryParse(entityName[entityName.Length - 1].ToString(), out num))
                    {
                        entityName = entityName.Substring(0, entityName.Length - 1);
                    }
                    else
                    {
                        break;
                    }

                }

                entity.ItemHex = String.Join(" ", fragment.ToArray());

                return entity;
            }

            return null;
        }

        /// <summary>
        /// 十六进制位片段中获取十进制
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="len"></param>
        /// <param name="fragment"></param>
        /// <param name="reverse"></param>
        /// <returns></returns>
        private int getDecFromFragmentSlice(int startIndex, int len, List<string> fragment, bool reverse)
        {
            string no = string.Empty;

            if (reverse)
            {
                for (int i = startIndex + len - 1; i > startIndex - 1; i--)
                {
                    no += fragment[i];
                }
            }
            else
            {
                for (int i = startIndex; i < startIndex + len; i++)
                {
                    no += fragment[i];
                }
            }

            return HexHelper.hexToDec(no);
        }

        /// <summary>
        /// Append logs in the log view
        /// </summary>
        /// <param name="text"></param>
        private void log(string text)
        {
            log(text, LOG_LEVEL.DEBUG);
        }

        /// <summary>
        /// Append logs in the log view
        /// </summary>
        /// <param name="text"></param>
        /// <param name="type"></param>
        private void log(string text, LOG_LEVEL logLevel)
        {
            int paramLogLevelNumber = getLogLevelNumberByText(logLevel.ToString());
            selectedLogLevelNumber = getLogLevelNumberByText(this.comboBox1.SelectedItem.ToString());

            if (paramLogLevelNumber < 0)
            {
                // LOG_LEVEL detected as NONE, only for split line prints
                this.richTextBox1.AppendText(text + System.Environment.NewLine);
            }
            else if (paramLogLevelNumber <= selectedLogLevelNumber)
            {
                // Indicates the specified log level
                int pos = this.richTextBox1.Text.Length;
                string message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ": [" + logLevel + "] " + text;
                this.richTextBox1.AppendText(message + System.Environment.NewLine);

                this.richTextBox1.Select(pos, message.Length);
                if (logLevel == LOG_LEVEL.ERROR)
                {
                    this.richTextBox1.SelectionColor = Color.Red;
                }
                else if (logLevel == LOG_LEVEL.WARNING)
                {
                    this.richTextBox1.SelectionColor = Color.Blue;
                }
            }

            //this.richTextBox1.ScrollToCaret();
        }

        /// <summary>
        /// Obtains the log level number from the specified log level text
        /// </summary>
        /// <param name="logLevelText"></param>
        /// <returns></returns>
        public int getLogLevelNumberByText(string logLevelText)
        {
            if (logLevelText != string.Empty)
            {
                string[] levelNames = Enum.GetNames(typeof(LOG_LEVEL));
                foreach (string levelName in levelNames)
                {
                    if (levelName.Equals(logLevelText))
                    {
                        return int.Parse(Enum.Format(typeof(LOG_LEVEL), Enum.Parse(typeof(LOG_LEVEL), logLevelText), "d"));
                    }
                }
            }

            return -1;
        }

        /// <summary>
        /// Refresh the form inputs with the specified application configuration
        /// </summary>
        private void updateForm()
        {
            this.updateForm(ApplicationConfig.AppConfig);
        }

        /// <summary>
        /// Refresh the form inputs with the specified application configuration
        /// </summary>
        /// <param name="appConfig">the application configuration entity</param>
        private void updateForm(ApplicationConfig appConfig)
        {
            if (appConfig != null)
            {
                this.txtFile.Text = appConfig.NmapFile;
                this.txtExportFolder.Text = appConfig.ExportFolder;

                if (this.txtFile.Text.Trim() != "")
                {
                    string fileName = Path.GetFileNameWithoutExtension(this.txtFile.Text.Trim());
                    if (ApplicationConfig.AppConfig.FilterNames.ContainsKey("rule_" + fileName))
                    {
                        this.txtAllowedItemPatterns.Text = ApplicationConfig.AppConfig.FilterNames["rule_" + fileName];
                    }
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowser_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (this.txtExportFolder.Text.Trim() != "")
            {
                dialog.SelectedPath = this.txtExportFolder.Text.Trim();
            }

            dialog.ShowDialog();
            this.txtExportFolder.Text = dialog.SelectedPath;
        }
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            selectedLogLevelNumber = getLogLevelNumberByText(this.comboBox1.SelectedItem.ToString());

            Thread thread = new Thread(new ThreadStart(doStart));
            thread.Start();
        }

        #endregion

    }
}
